﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using LibMinecraft.Model;
using LibMinecraft.Server;
using System.Reflection;
using System.Diagnostics;
using System.Threading;
using PartyCraftServer.Commands;
using LibMinecraft.Model.Packets;
using LibMinecraft.Model.Entities;
using PartyCraftServer.Plugins;

namespace PartyCraftServer
{
    public class Program
    {
        static StreamWriter logStream;

        /// <summary>
        /// Run PartyCraft
        /// </summary>
        static void Main(string[] args)
        {
            PartyCraft.SettingsDirectory = Directory.GetCurrentDirectory();

            foreach (string arg in args)
            {
                if (arg.StartsWith("-sd:"))
                    PartyCraft.SettingsDirectory = arg.Substring(4); // TODO: More command line options
            }

            PartyCraft.InitializeSettings();
            logStream = new StreamWriter(PartyCraft.Settings["server.logfile"], true);
            PartyCraft.OnLog += PartyCraft_OnLog;

            PartyCraft.Run();

            string consoleInput = "";
            RemoteClient consoleClient = new RemoteClient(); // The console user is a fake client
            consoleClient.PacketQueue = new Queue<Packet>();
            consoleClient.PlayerEntity = new PlayerEntity()
            {
                ID = -1,
                Location = Vector3.Zero,
                Name = "CONSOLE",
                WorldIndex = 0,
            };
            consoleClient.Tags["op"] = true;
            while (true)
            {
                consoleInput = Console.ReadLine();
                Command.Execute(consoleClient, consoleInput);
                while (consoleClient.PacketQueue.Count != 0)
                {
                    Packet packet = consoleClient.PacketQueue.Dequeue(); // Dequeue any packets added by the command
                    if (packet.PacketID == PacketID.ChatUpdate)
                    {
                        Console.WriteLine((packet as ChatMessagePacket).Message);
                    }
                }
            }
        }

        static void PartyCraft_OnLog(object sender, LogEventArgs e)
        {
            Console.WriteLine(e.Text);
            logStream.WriteLine(e.Text);
            logStream.Flush();
        }
    }
}
